package com.lagou.server;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

public class RequestProcess extends Thread{
    private Map<String,HttpServlet> servletMap;
    private Socket socket;

  /*  public RequestProcess(Map<String, HttpServlet> servletMap, Socket socket) {
        this.servletMap = servletMap;
        this.socket = socket;
    }*/
    RequestProcess(Socket socket){
        this.socket=socket;
    }

    @Override
    public void run() {
        /*try{
            InputStream inputStream = socket.getInputStream();
            Request request=new Request(inputStream);
            Response response=new Response(socket.getOutputStream());
            if(servletMap.get(request.getUrl())==null){
                response.outPutHtml(request.getUrl());
            }else{
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }

            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }*/
        //6.0
        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();
            //封装请求和响应对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            //请求url
            String url = request.getUrl();
            //获取上下文
            String context = url.substring(0).substring(0, url.substring(1).indexOf("/") + 1);
            //真正请求的url
            String realUrl = url.replace(context, "");
            boolean falg = false;
            //上下文
            BaseContext context1 = null;
            //判断上下文

            for (BaseContext con : ResourcesLoad.engine.getHosts().get(0).getContextList()) {
                String name = con.getBaseName();
                if (context.equalsIgnoreCase("/" + name)) {
                    context1 = con;
                    //获取wrapper  处理请求
                    List<ContextWrapper> wrappersList = context1.getWrappersList();
                    for (ContextWrapper wrapper : wrappersList) {
                        if (realUrl.equals(wrapper.getUrl())) {
                            falg = true;
                            HttpServlet httpServlet = (HttpServlet) wrapper.getObject();
                            httpServlet.service(request,response);
                        }
                    }
                    break;
                }
            }
            if (!falg) {
                response.output((HttpProtocoUtil.getHttpHeader404()));
                return;
            }
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
